import {
  Actor,
  HttpAgent,
  // IDL,
  ActorSubclass,
} from '@dfinity/agent';

// Canister ID
// const canisterId = 'mxzaz-hqaaa-aaaar-qaada-cai';
const canisterId = 'spdsf-5yaaa-aaaam-adcnq-cai';
import {idlFactory} from './icrc1_ledger_canister_backend.ts';
import {Principal} from '@dfinity/principal';
import {Secp256k1KeyIdentity} from '@dfinity/identity';

// The minter's identity_pem
const identity_pem_buf = new Uint8Array([
  0xf4, 0x68, 0x81, 0xe2, 0xd8, 0x83, 0xd1, 0x27, 0x18, 0x94, 0x37, 0x60, 0x43,
  0xc0, 0x26, 0xf3, 0xb0, 0xbd, 0x3b, 0xa4, 0xd8, 0xb6, 0xad, 0x6a, 0xdb, 0x8f,
  0x39, 0xda, 0xdd, 0x33, 0x9b, 0x0e,
]);

let identity = Secp256k1KeyIdentity.fromSecretKey(identity_pem_buf);
// Initialize an agent to interact with the canister
const agent = new HttpAgent({
  identity: identity,
  // host: 'http://localhost:4943', // Ensure this matches the network you're interacting with
  host: 'https://a4gq6-oaaaa-aaaab-qaa4q-cai.raw.icp0.io',
});

// Uncomment this line if you are using a local replica
agent.fetchRootKey();

// Create an actor with the specified canister ID and IDL
const canisterActor: ActorSubclass = Actor.createActor(idlFactory as any, {
  agent,
  canisterId,
});

async function transfer(receiver: string, amount: number) {
  try {
    const principalOwner = Principal.fromText(receiver);
    const mintResult = await canisterActor.icrc1_transfer({
      from_subaccount: [],
      to: {
        owner: principalOwner,
        subaccount: [],
      },
      amount,
      fee: [],
      memo: [],
      created_at_time: [],
    });
    console.log(
      `Successfully Mint to ${receiver}. The amount is ${amount}. The TransactionID is: ${JSON.stringify(
        mintResult,
        (key, value) => (typeof value === 'bigint' ? value.toString() : value),
      )}`,
    );
    return mintResult;
  } catch (error) {
    console.error('Error fetching balance:', error);
    throw error;
  }
}

const receiver =
  'wirxf-7fcvv-up7ph-i4t55-cm6qg-sbcb5-ue7j7-e3yzh-txcb2-egiao-bae';
transfer(receiver, 1000);
